%%@ author Grupp 3
%%@ version 1.5
%%@ copyright Grupp 3
%%@ doc The module contains functions for operating a database of users.  

-module(userman).
-export([addUser/2, login/2]).

-include_lib("eunit/include/eunit.hrl").

%% @doc Creates a new User named Name with password Password in the database Projects. Return ok if Name is not already taken, else error.
%% @spec addUser(Name, Password) -> atom() | error
%% where 
%% Name = string()
%% Password = string()

addUser(Name, Password) -> 
	dets:open_file(userlist,[]),	
	case dets:member(userlist, Name) of
	false ->
		dets:insert(userlist, {Name, Password}),
		dets:close(userlist);
	true ->	
		dets:close(userlist),
		{error,"A user with that name already exists"}
	end.
	
%% @doc Return ok if a user with username Name and password Password exists in the database. Else error.
%% @spec login(Name, Password) -> atom() | error
%% where 
%% Name = string()
%% Password = string()

login(Name, Password) -> 
	dets:open_file(userlist,[]),
	case dets:member(userlist, Name) of
	true ->
		[X] = dets:lookup(userlist, Name),	
		case Password == element(2, X) of
		false ->
			dets:close(userlist),			
			{error,"Wrong Password"};		
		true ->	
			dets:close(userlist),
			ok
		end;
	false ->
		dets:close(userlist),
		{error,"A user with that name doesn't exists"}		

	end.







	%%% EUnit test cases here %%%


%Kontrollerar att det går att lägga till en ny användare
addUser_test() -> 
	dets:open_file(userlist, []),
	userman:addUser("user_test", "password_test"),
  	?assertEqual(true, dets:member(userlist, "user_test")),
	dets:delete(userlist, "user_test"),
	dets:close(userlist).


%Kontrollerar att man får ett error om man försöker lägga till en användare som redan finns
addUser_error_test() -> 
	dets:open_file(userlist, []),
	userman:addUser("user_test", "password_test"),
  	?assertMatch({error, _}, userman:addUser("user_test", "password_test")),
	dets:delete(userlist, "user_test"),
	dets:close(userlist).



%Kontrollerar att det går att lägga till en ny användare
login_test() -> 
	dets:open_file(userlist, []),
	userman:addUser("user_test", "password_test"),
  	?assertEqual(ok, login("user_test", "password_test")),
	dets:delete(userlist, "user_test"),
	dets:close(userlist).


%Kontrollerar att det går att lägga till en ny användare
login_user_error_test() -> 
	dets:open_file(userlist, []),
  	?assertMatch({error, _}, login("user_test", "password_test")),
	dets:close(userlist).


%Kontrollerar att det går att lägga till en ny användare
login_password_error_test() -> 
	dets:open_file(userlist, []),
	userman:addUser("user_test", "password_test"),
  	?assertMatch({error, _}, login("user_test", "wrong_password")),
	dets:delete(userlist, "user_test"),
	dets:close(userlist).


